3 sum Algorithm

The 3 Sum Algorithm is a popular computational problem that aims to find all the unique triplets in a given array of integers such that the sum of the three elements in the triplet is equal to zero. The algorithm has various applications in computer science, including computational geometry, number theory, and complexity analysis. It is often used as a base problem to solve more complex problems or to create optimal solutions for certain problems. The algorithm typically starts by sorting the given array of integers in ascending order. Then, using a nested loop, it iterates through each element in the array and sets two pointers, one at the element immediately following the current element and another at the end of the array. It then checks the sum of the values at the current element and the two pointers. If the sum is equal to zero, it records the triplet and moves both pointers towards each other. If the sum is less than zero, it moves the left pointer to the right. If the sum is greater than zero, it moves the right pointer to the left. This process continues until the pointers meet, ensuring that all unique triplets with a sum of zero are found. The algorithm has a time complexity of O(n^2), as it involves sorting the array and iterating through the elements using nested loops.
package Others;

import java.util.Scanner;
import java.util.Arrays;

/**
 * To find triplet equals to given sum in complexity O(n*log(n))
 * 
 *
 * Array must be sorted 
 *
 * @author Ujjawal Joshi
 * @date 2020.05.18
 *
 * Test Cases:
 	Input:
 *	6 //Length of array
 	12 3 4 1 6 9
 	target=24
 *	Output:3 9 12
 *	Explanation: There is a triplet (12, 3 and 9) present
	in the array whose sum is 24. 
 *
 *

 */


class threesum{
	public static void main(String args[])
	{
		Scanner sc =new Scanner(System.in);
		int n=sc.nextInt(); //Length of an array

		int a[]=new int[n];

		for(int i=0;i<n;i++)
		{
			a[i]=sc.nextInt();
		}
		System.out.println("Target");
		int n_find=sc.nextInt();

		Arrays.sort(a);	// Sort the array if array is not sorted

		for(int i=0;i<n;i++){	

			int l=i+1,r=n-1;

			while(l<r){
				if(a[i]+a[l]+a[r]==n_find) {System.out.println(a[i]+" "+ a[l]+" "+a[r]);break;} //if you want all the triplets write l++;r--; insted of break; 
				else if(a[i]+a[l]+a[r]<n_find) l++;
				else r--;
			}
		}
		

		
	}
}

LANGUAGE:

DARK MODE: